package tool

import (
	"fmt"
	"io"
	"net/http"
	"time"
)

// 定义全局HTTP客户端以重用连接
var defaultClient = &http.Client{
	Timeout: time.Duration(60) * time.Second,
}

func Get(url string) (io.ReadCloser, error) {
	if url == "" {
		return nil, fmt.Errorf("URL cannot be empty")
	}
	
	resp, err := defaultClient.Get(url)
	if err != nil {
		return nil, fmt.Errorf("failed to make HTTP request to '%s': %w", url, err)
	}
	
	if resp.StatusCode != 200 {
		// 尝试读取错误响应体以获取更多信息
		defer resp.Body.Close()
		
		// 限制读取错误响应体的大小以避免大响应体占用过多内存
		limitReader := io.LimitReader(resp.Body, 1024)
		bodyBytes, _ := io.ReadAll(limitReader)
		
		return nil, fmt.Errorf("HTTP error: status code %d for URL '%s', response body: %s", 
			resp.StatusCode, url, string(bodyBytes))
	}
	
	return resp.Body, nil
}



